﻿using Fiddler;
using System;
using System.Text;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

using System.IO;
using Newtonsoft.Json;
using System.Security.Cryptography; //MD5
//using Securitys;
using System.Net;
using System.Text.RegularExpressions;
using System.Collections;
using System.Web.Script.Serialization;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;

namespace FiddlerEx_Inspector
{
    public class CommonMethods
    {
        //加解密表单信息
        private static string VIEWSTATE = "";
        private static string VIEWSTATEGENERATOR = "";
        private static string EVENTVALIDATION = "";
        private static bool updatedFormInfo = false;

        private static string decryptUrl = FiddlerApplication.Prefs.GetStringPref("fiddlerex.urlconfig.decrypturl", "");
        private static int reqTimeOut = FiddlerApplication.Prefs.GetInt32Pref("fiddlerex.func.timeout", 3000);

        public CommonMethods()
        {
        }

        public void WriteLog(StreamWriter sr, string log_string)
        {
            sr.WriteLine(log_string);
            sr.Flush();
            //sr.Close();
        }

        internal static void DoRichTextSearch(RichTextBox rtbSearch, string sSearchFor, bool bHighlightAll)
        {
            if (rtbSearch.TextLength >= 1)
            {
                if (StringExtensions.OICStartsWith(sSearchFor, "regex:"))
                {
                    FiddlerApplication.DoNotifyUser("Unfortunately, this Inspector cannot perform regular expression searches. Please use SyntaxView instead.", "RegEx Unsupported");
                }
                if (bHighlightAll)
                {
                    try
                    {
                        LockWindowUpdate(rtbSearch.Handle);
                        rtbSearch.SelectionStart = 0;
                        rtbSearch.SelectionLength = rtbSearch.TextLength;
                        rtbSearch.SelectionBackColor = rtbSearch.BackColor;
                        rtbSearch.SelectionLength = 0;
                        if (!string.IsNullOrEmpty(sSearchFor))
                        {
                            int num = rtbSearch.Find(sSearchFor, 0, RichTextBoxFinds.None);
                            int num2 = num;
                            while (num > -1)
                            {
                                rtbSearch.SelectionBackColor = Color.Yellow;
                                num++;
                                if (num >= rtbSearch.TextLength)
                                {
                                    break;
                                }
                                num = rtbSearch.Find(sSearchFor, num, RichTextBoxFinds.None);
                            }
                            if (num2 > -1)
                            {
                                rtbSearch.SelectionLength = 0;
                                rtbSearch.SelectionStart = num2;
                            }
                        }
                        return;
                    }
                    finally
                    {
                        LockWindowUpdate(IntPtr.Zero);
                    }
                }
                int start = Math.Min(rtbSearch.SelectionStart + 1, rtbSearch.TextLength);
                rtbSearch.Find(sSearchFor, start, RichTextBoxFinds.None);
            }
        }

        internal static int GetLineCountForTextBox(TextBoxBase txtBox)
        {
            return (int)SendMessage(txtBox.Handle, 0xba, 0, 0);
        }

        internal static string GetTreeNodeFullText(TreeNode oTN)
        {
            if (oTN.Tag == null)
            {
                return oTN.Text;
            }
            return (oTN.Tag as string);
        }

        [DllImport("user32.dll")]
        private static extern bool LockWindowUpdate(IntPtr hWndLock);
        internal static void ScrollDown(RichTextBox rtb)
        {
            SendMessage(rtb.Handle, 0x115, 1, 0);
        }

        internal static void ScrollUp(RichTextBox rtb)
        {
            SendMessage(rtb.Handle, 0x115, 0, 0);
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        internal static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, int lParam);
        internal static void SetTreeNodeLimitedText(TreeNode oTN, string sText)
        {
            string str = sText;
            if (str.Length > 0x103)
            {
                str = Utilities.TrimTo(str, 0x102) + "…";
            }
            oTN.Text = str;
            if (str != sText)
            {
                oTN.Tag = sText;
            }
        }

        /// <summary>
        /// 判断字符串是否为JSON格式
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static Boolean IsJson(string json)
        {
            if (json.Trim() == "")
            {
                return false;
            }
            JavaScriptSerializer js = new JavaScriptSerializer();
            try
            {
                Dictionary<string, object> dic = js.Deserialize<Dictionary<string, object>>(json);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 获取Json节点值，注：节点字段名区分大小写
        /// </summary>
        /// <param name="json_string"></param>
        /// <param name="node"></param>
        /// <returns></returns>
        public static ArrayList GetJsonValue(string json_string, string node)
        {
            ArrayList result = new ArrayList();
            if (IsJson(json_string) && node != "")
            {
                JavaScriptSerializer js = new JavaScriptSerializer();
                try
                {
                    Dictionary<string, object> dic = js.Deserialize<Dictionary<string, object>>(json_string);
                    if (dic != null)
                    {
                        ArrayList res = new ArrayList();
                        result = Test(dic, node, res);
                    }
                    else
                    {
                        Fiddler.FiddlerApplication.Log.LogString("反序列化失败：" + json_string);
                        result.Add("");
                        return result;
                    }
                    if (result.Count == 0)
                    {
                        //Fiddler.FiddlerApplication.Log.LogString("未获取到：" + node + "的值\n" + json_string);
                        result.Add("");
                    }
                    return result;
                }
                catch (Exception e)
                {
                    //Fiddler.FiddlerApplication.Log.LogString("获取" + node + "字段值失败：" + e.ToString());
                    result.Add("");
                    return result;
                }
            }
            result.Add("");
            return result;
        }

        public static ArrayList Test(Dictionary<string, object> dictionary, string node, ArrayList result)
        {
            foreach (KeyValuePair<string, object> item in dictionary)
            {
                try
                {
                    dictionary = (Dictionary<string, object>)(item.Value);
                    if (dictionary != null)
                    {
                        Test(dictionary, node, result);
                    }
                }
                catch (Exception e)
                {
                    if (item.Value is ArrayList)//判断子节点是否是数组
                    {
                        foreach (object obj in (ArrayList)item.Value)
                        {
                            try
                            {
                                dictionary = (Dictionary<string, object>)(obj);
                                if (dictionary != null)
                                {
                                    Test(dictionary, node, result);
                                }
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                    }
                    else if (item.Key.ToString() == node)
                    {
                        string value = item.Value.ToString();
                        result.Add(value);
                    }
                    else
                    {
                        //FiddlerApplication.Log.LogString("GetJsonValue(): " + node + " -- Node not found！");
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 获取表单信息
        /// </summary>
        /// <param name="decryptUrl"></param>
        private static bool GetFormInfo(string url)
        {
            if (!updatedFormInfo)
            {
                try
                {
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                    req.Method = "POST";
                    req.ContentType = "application/x-www-form-urlencoded";
                    req.Timeout = reqTimeOut;
                    req.Proxy = null;

                    #region 添加Post 参数

                    byte[] data = Encoding.UTF8.GetBytes("");

                    req.ContentLength = data.Length;
                    using (Stream reqStream = req.GetRequestStream())
                    {
                        reqStream.Write(data, 0, data.Length);
                        reqStream.Close();
                    }

                    #endregion

                    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                    Stream stream = resp.GetResponseStream();
                    //获取响应内容  
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        string input = reader.ReadToEnd();
                        string[] resultString = Regex.Split(input, "name=\"__VIEWSTATE\"", RegexOptions.IgnoreCase);

                        foreach (string result in resultString)
                        {
                            if (result.Contains("id=\"__VIEWSTATE\""))
                            {
                                VIEWSTATE = Regex.Unescape(result.Split('"')[3]);
                            }
                        }

                        resultString = Regex.Split(input, "name=\"__VIEWSTATEGENERATOR\"", RegexOptions.IgnoreCase);

                        foreach (string result in resultString)
                        {
                            if (result.Contains("id=\"__VIEWSTATEGENERATOR\""))
                            {
                                VIEWSTATEGENERATOR = Regex.Unescape(result.Split('"')[3]);
                            }
                        }

                        resultString = Regex.Split(input, "name=\"__EVENTVALIDATION\"", RegexOptions.IgnoreCase);

                        foreach (string result in resultString)
                        {
                            if (result.Contains("id=\"__EVENTVALIDATION\""))
                            {
                                EVENTVALIDATION = Regex.Unescape(result.Split('"')[3]);
                            }
                        }
                    }

                    updatedFormInfo = true;
                    return true;
                }
                catch (Exception ex)
                {
                    updatedFormInfo = false;
                    FiddlerApplication.Log.LogString("GetFormInfo(): " + ex.Message);
                    return false;
                }
            }
            updatedFormInfo = true;
            return true;
        }

        /// <summary>
        /// 备用加密方法
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        private static string GetBackupEncResponse(string content)
        {
            string url = FiddlerApplication.Prefs.GetStringPref("fiddlerex.urlconfig.backupdecrypturl", "");
            if (GetFormInfo(url))
            {
                try
                {
                    string result = "";
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                    req.Method = "POST";
                    req.ContentType = "application/x-www-form-urlencoded";
                    req.Timeout = reqTimeOut;
                    req.Proxy = null;

                    #region 添加Post 参数

                    byte[] data = Encoding.UTF8.GetBytes("__VIEWSTATE=" + Utilities.UrlEncode(VIEWSTATE) + "&__VIEWSTATEGENERATOR=" + Utilities.UrlEncode(VIEWSTATEGENERATOR) + "&__EVENTVALIDATION="
                        + Utilities.UrlEncode(EVENTVALIDATION) + "&txtCode="
                        + Utilities.UrlEncode(content)
                        + "&txtEncryptCode=&btnEncrypt=%e5%8a%a0%e5%af%86&txtDecryptCode="
                        );
                    req.ContentLength = data.Length;
                    using (Stream reqStream = req.GetRequestStream())
                    {
                        reqStream.Write(data, 0, data.Length);
                        reqStream.Close();
                    }

                    #endregion

                    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                    Stream stream = resp.GetResponseStream();
                    //获取响应内容  
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        result = reader.ReadToEnd();
                    }
                    //MessageBox.Show(result);
                    string[] resultString = Regex.Split(result, "textarea", RegexOptions.IgnoreCase);
                    foreach (string res in resultString)
                    {
                        if (res.Contains("id=\"txtEncryptCode\""))
                        {
                            string re = Regex.Unescape(res.Split('>')[1].Split('<')[0].Replace("&quot;", "\"").Replace("&#165;", "¥").Replace("&#183;", "·")).Trim();
                            return (re != "" ? re : content);
                        }
                    }
                    return content;
                }
                catch (Exception ex)
                {
                    Fiddler.FiddlerApplication.Log.LogString("GetBackupEncResponse(): " + ex.Message);
                    return content;
                }
            }
            return content;
        }

        /// <summary>
        /// 备用解密方法
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        private static string GetBackupDecResponse(string content)
        {
            string url = FiddlerApplication.Prefs.GetStringPref("fiddlerex.urlconfig.backupdecrypturl", "");
            if (GetFormInfo(url))
            {
                try
                {
                    string result = "";
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                    req.Method = "POST";
                    req.ContentType = "application/x-www-form-urlencoded";
                    req.Timeout = reqTimeOut;
                    req.Proxy = null;

                    #region 添加Post 参数

                    byte[] data = Encoding.UTF8.GetBytes("__VIEWSTATE=" + Utilities.UrlEncode(VIEWSTATE) + "&__VIEWSTATEGENERATOR=" + Utilities.UrlEncode(VIEWSTATEGENERATOR) + "&__EVENTVALIDATION="
                        + Utilities.UrlEncode(EVENTVALIDATION) + "&txtCode=&txtEncryptCode="
                        + Utilities.UrlEncode(content)
                        + "&Button1=%E8%A7%A3%E5%AF%86&txtDecryptCode="
                        );
                    req.ContentLength = data.Length;
                    using (Stream reqStream = req.GetRequestStream())
                    {
                        reqStream.Write(data, 0, data.Length);
                        reqStream.Close();
                    }

                    #endregion

                    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                    Stream stream = resp.GetResponseStream();
                    //获取响应内容  
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        result = reader.ReadToEnd();
                    }
                    //MessageBox.Show(result);
                    string[] resultString = Regex.Split(result, "textarea", RegexOptions.IgnoreCase);
                    foreach (string res in resultString)
                    {
                        if (res.Contains("id=\"txtDecryptCode\""))
                        {
                            string re = ReplaceSpecialString(Regex.Unescape(res.Split('>')[1].Split('<')[0].Replace("&quot;", "\"").Replace("&#165;", "¥").Replace("&#183;", "·")).Replace("&lt;", "<").Replace("&gt;", ">").Trim());
                            return (re != "" ? re : content);
                        }
                    }
                    return content;

                }
                catch (Exception ex)
                {
                    Fiddler.FiddlerApplication.Log.LogString("GetBackupDecResponse(): " + ex.Message);
                    return content;
                }
            }
            return content;
        }

        /// <summary>
        /// 加密方法
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static Dictionary<string, string> GetEncResponse(HTTPRequestHeaders headers, string content)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            try
            {
                string encData = "";
                string userAgent = "chebada";
                if (String.IsNullOrEmpty(content))
                    return result;
                if (headers != null)
                {
                    userAgent = headers["User-Agent"];
                }
                if (headers != null && headers["Host"].Contains("vstlog.17usoft.com"))
                {
                    encData = GetBodyDecryptOrEncryptData("trackaes", "enc", content, "chebada");
                }
                else
                {
                    encData = GetBodyDecryptOrEncryptData("appaes", "enc", content, userAgent);
                }

                JObject jsonObject = JObject.Parse(encData);
                string code = jsonObject.SelectToken("code").ToString();
                if (code == "200")
                {
                    result.Add("encData", jsonObject.SelectToken("data.str").ToString());
                    result.Add("reqreqdata", jsonObject.SelectToken("data.reqreqdata").ToString());
                    result.Add("reqrsqdata", jsonObject.SelectToken("data.reqrsqdata").ToString());
                }
                else
                {
                    FiddlerApplication.Log.LogString("GetEncResponse：code: " + code + ", message: " + jsonObject.SelectToken("message").ToString());
                }
            }
            catch (Exception ex)
            {
                FiddlerApplication.Log.LogString("GetEncResponse：" + decryptUrl + "\r\nHost:" + headers["Host"] + "\r\n请求：" + content);
            }
            return result;
        }
        /// <summary>
        /// 解密方法
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string GetDecResponse(HTTPRequestHeaders headers, string content)
        {
            try
            {
                string result = "";
                string userAgent = "chebada";
                if (String.IsNullOrEmpty(content))
                    return result;
                if (headers != null)
                {
                    userAgent = headers["User-Agent"];
                }
                if (headers != null && headers["Host"].Contains("vstlog.17usoft.com"))
                {
                    result = GetBodyDecryptOrEncryptData("trackaes", "des", content, "chebada");
                }
                else
                {
                    result = GetBodyDecryptOrEncryptData("appaes", "des", content, userAgent);
                }

                JObject jsonObject = JObject.Parse(result);
                string code = jsonObject.SelectToken("code").ToString();
                if (code == "200")
                {
                    return ReplaceSpecialString(jsonObject.SelectToken("data.str").ToString());
                }
                else
                {
                    FiddlerApplication.Log.LogString("GetDecResponse：code: " + code + ", message: " + jsonObject.SelectToken("message").ToString());
                    return GetBackupDecResponse(content);
                }
            }
            catch (Exception ex)
            {
                FiddlerApplication.Log.LogString("GetDecResponse：" + decryptUrl + "\r\nHost:" + headers["Host"] + "\r\n请求：" + content);
                return GetBackupDecResponse(content);
            }
        }

        public static string GetBodyDecryptOrEncryptData(string type, string action, string aesBody, string userAgent)
        {
            JObject paramObj = new JObject();
            paramObj.Add("type", type);
            paramObj.Add("actype", action);
            paramObj.Add("aesdata", aesBody);
            paramObj.Add("user_agent", userAgent);

            string data = GetHttpResponse(paramObj.ToString());

            return data;
        }

        public static string GetHttpResponse(string param)
        {
            string result = "";
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(decryptUrl);
                req.Method = "POST";
                req.ContentType = "application/json";
                req.Timeout = reqTimeOut;
                req.Proxy = null;

                #region 添加Post 参数

                byte[] data = Encoding.UTF8.GetBytes(param);
                req.ContentLength = data.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }

                #endregion

                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();
                //获取响应内容  
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
                //MessageBox.Show(result);

            }
            catch (Exception ex)
            {
                FiddlerApplication.Log.LogString("GetHttpResponse：" + decryptUrl + "\r\n请求：" + param);

            }
            return result;
        }

        /// <summary>
        /// 获取MD5值
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string GetMD5(string value)
        {
            //string str_value;
            //if (value.Length <= 20)
            //{
            //    str_value = value;
            //}
            //else
            //{
            //    str_value = value.Substring(0, 20);
            //}
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] data = md5.ComputeHash(Encoding.GetEncoding("utf-8").GetBytes(value));
            StringBuilder builder = new StringBuilder(32);
            for (int i = 0; i < data.Length; i++)
            {
                builder.Append(data[i].ToString("x2"));
            }
            return builder.ToString();
        }
        /// <summary>
        /// 转换成JSON缩进格式
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ConvertJsonString(string str)
        {
            if (IsJson(str))
            {
                try
                {
                    //格式化json字符串
                    JsonSerializer serializer = new JsonSerializer();
                    TextReader tr = new StringReader(str);
                    JsonTextReader jtr = new JsonTextReader(tr);
                    object obj = serializer.Deserialize(jtr);
                    if (obj != null)
                    {
                        StringWriter textWriter = new StringWriter();
                        JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
                        {
                            Formatting = Formatting.Indented,
                            Indentation = 4,
                            IndentChar = ' '
                        };
                        serializer.Serialize(jsonWriter, obj);
                        return textWriter.ToString();
                    }
                    else
                    {
                        return str;
                    }
                }
                catch (Exception e)
                {
                    FiddlerApplication.Log.LogString(e.ToString());
                    return str;
                } 
            }
            return str;
        }
        /// <summary>
        /// 替换表情等不识别字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static string ReplaceSpecialString(string str)
        {
            string result = Regex.Replace(str, @"\p{Cs}", "");
            result = JsonPre(result);
            return result;
        }
        /// <summary>
        /// 针对特殊JSON数据预处理
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static string JsonPre(string json)
        {
            try
            {
                if (json.Contains("={\""))
                {
                    string[] strArr = json.Split('=');
                    for (int i = 1; i < strArr.Length; i++)
                    {
                        int index = strArr[i].IndexOf("}\"");
                        string str1 = strArr[i].Substring(0, index);
                        str1 = str1.Replace("\"", "\\" + "\"");
                        json = json.Replace(strArr[i].Substring(0, index), str1);
                    }
                }
                if (json.Contains(":\"<p"))
                {
                    int index = json.IndexOf("<");
                    int lastIndex = json.LastIndexOf(">");
                    string str = json.Substring(index, lastIndex - index);
                    string str1 = str.Replace("\"", "\\" + "\"");
                    json = json.Replace(str, str1);
                }
            }
            catch (Exception e)
            {
                FiddlerApplication.Log.LogString("JsonPre: " + e.Message);
            }
            return json;
        }

        /// <summary>
        /// 获取请求header头reqdata值
        /// </summary>
        /// <param name="reqbody"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public string GetReqReqData(string reqbody)
        {
            try
            {
                string result = "";
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(decryptUrl);
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.Timeout = 3000;
                req.Proxy = null;

                #region 添加Post 参数

                byte[] data = Encoding.UTF8.GetBytes("type=1&text=" + Utilities.UrlEncode(reqbody));
                req.ContentLength = data.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }

                #endregion

                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();
                //获取响应内容  
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
                //MessageBox.Show(result);
                string code = GetJsonValue(result, "code")[0].ToString();

                if (code == "200")
                {
                    return GetJsonValue(result, "reqreqdata")[0].ToString();
                }
                else
                {
                    return "获取请求reqdata时，code=" + code;
                }
            }
            catch (Exception ex)
            {
                return "获取请求reqdata失败";
            }
        }
        /// <summary>
        /// 获取响应header头reqdata值
        /// </summary>
        /// <param name="rspBody"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public string GetRspReqData(string rspBody)
        {
            try
            {
                string result = "";
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(decryptUrl);
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.Timeout = 3000;
                req.Proxy = null;

                #region 添加Post 参数

                byte[] data = Encoding.UTF8.GetBytes("type=1&text=" + Utilities.UrlEncode(rspBody));
                req.ContentLength = data.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }

                #endregion

                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();
                //获取响应内容  
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
                //MessageBox.Show(result);
                string code = GetJsonValue(result, "code")[0].ToString();
                if (code == "200")
                {
                    return GetJsonValue(result, "rspreqdata")[0].ToString();
                }
                else
                {
                    return "获取响应reqdata时，code=" + code;
                }
            }
            catch (Exception ex)
            {
                return "获取响应reqdata失败";
            }
        }

        public static string GetDocumentTextWithJson(string json)
        {
            #region json着色
            string html = "<html>\r\n" +
            "	<head>\r\n" +
            "		<meta name=\"viewport\" content=\"width=device-width, minimum-scale=0.1\">\r\n" +
            "		<title>JsonViewer</title>\r\n" +
            "		<style>\r\n" +
            "			body {\r\n" +
            "				font-family: Lucida Console, Georgia;\r\n" +
            "				font-size: 13px;\r\n" +
            "				background-color: #ECECEC;\r\n" +
            "				color: #000000;\r\n" +
            "				border: solid 1px #CECECE;\r\n" +
            "               margin: 0px;\r\n" +
            "			}\r\n" +
            "			.ObjectBrace {\r\n" +
            "				color: #00AA00;\r\n" +
            "				font-weight: bold;\r\n" +
            "			}\r\n" +
            "			.ArrayBrace {\r\n" +
            "				color: #0033FF;\r\n" +
            "				font-weight: bold;\r\n" +
            "			}\r\n" +
            "			.PropertyName {\r\n" +
            "				color: #CC0000;\r\n" +
            "				font-weight: bold;\r\n" +
            "			}\r\n" +
            "			.String {\r\n" +
            "				color: #007777;\r\n" +
            "			}\r\n" +
            "			.Number {\r\n" +
            "				color: #AA00AA;\r\n" +
            "			}\r\n" +
            "			.Boolean {\r\n" +
            "				color: #0000FF;\r\n" +
            "			}\r\n" +
            "			.Function {\r\n" +
            "				color: #AA6633;\r\n" +
            "				text-decoration: italic;\r\n" +
            "			}\r\n" +
            "			.Null {\r\n" +
            "				color: #0000FF;\r\n" +
            "			}\r\n" +
            "			.Comma {\r\n" +
            "				color: #000000;\r\n" +
            "				font-weight: bold;\r\n" +
            "			}\r\n" +
            "			code, pre {\r\n" +
            "				padding: 0 3px 2px;\r\n" +
            "				font-family: Menlo,Monaco,Consolas,\"Courier New\",monospace;\r\n" +
            "				font-size: 12px;\r\n" +
            "				color: #333333;\r\n" +
            "				-webkit-border-radius: 3px;\r\n" +
            "				-moz-border-radius: 3px;\r\n" +
            "				border-radius: 3px;\r\n" +
            "			}\r\n" +
            "		</style>\r\n" +
            "	</head>\r\n" +
            "	<body onload=\"Process()\">\r\n" +
            "		<div id=\"Canvas\">Please wait...</div>\r\n" +
            "	</body>\r\n" +
            "	<script>\r\n" +
            "		window.SINGLE_TAB = \"  \";\r\n" +
            //"		window.ImgCollapsed = \"" + Application.StartupPath.Replace("\\", "/") + "/Collapsed.gif\";\r\n" +
            //"		window.ImgExpanded = \"" + Application.StartupPath.Replace("\\", "/") + "/Expanded.gif\";\r\n" +
            "		window.ImgCollapsed = \"\";\r\n" +
            "		window.ImgExpanded = \"\";\r\n" +
            "		window.QuoteKeys = true;\r\n" +
            "		function $id(id){ return document.getElementById(id); }\r\n" +
            "		function IsArray(obj) {\r\n" +
            "		  return  obj && \r\n" +
            "				  typeof obj === 'object' && \r\n" +
            "				  typeof obj.length === 'number' &&\r\n" +
            "				  !(obj.propertyIsEnumerable('length'));\r\n" +
            "		}\r\n" +
            "\r\n" +
            "		function Process(){\r\n" +
            "		  SetTab();\r\n" +
            "		  window.IsCollapsible = true; //显示控制收起/展开 //$id(\"CollapsibleView\").checked;\r\n" +
            "		  var json = \"" + json.Trim() + "\"; \r\n" +
            "		  var html = \"\";\r\n" +
            "		  try{\r\n" +
            "			if(json == \"\"){ json = \"\\\"\\\"\";return;}\r\n" +
            "			var obj = eval(\"[\"+json+\"]\");\r\n" +
            "			html = ProcessObject(obj[0], 0, false, false, false);\r\n" +
            "			$id(\"Canvas\").innerHTML = \"<PRE class='CodeContainer'>\"+html+\"</PRE>\";\r\n" +
            "		  }catch(e){\r\n" +
            "			//alert(\"JSON数据格式不正确:\\n\"+e.message);\r\n" +
            "			$id(\"Canvas\").innerHTML = json;\r\n" +
            "		  }\r\n" +
            "		}\r\n" +
            "		\r\n" +
            "		window._dateObj = new Date();\r\n" +
            "		window._regexpObj = new RegExp();\r\n" +
            "		function ProcessObject(obj, indent, addComma, isArray, isPropertyContent){\r\n" +
            "		  var html = \"\";\r\n" +
            "		  var comma = (addComma) ? \"<span class='Comma'>,</span> \" : \"\"; \r\n" +
            "		  var type = typeof obj;\r\n" +
            "		  var clpsHtml =\"\";\r\n" +
            "		  if(IsArray(obj)){\r\n" +
            "			if(obj.length == 0){\r\n" +
            "			  html += GetRow(indent, \"<span class='ArrayBrace'>[ ]</span>\"+comma, isPropertyContent);\r\n" +
            "			}else{\r\n" +
            "			  clpsHtml = window.IsCollapsible ? \"<span><img style='cursor:pointer' src=\\\"\"+window.ImgExpanded+\"\\\" onClick=\\\"ExpImgClicked(this)\\\" /></span><span class='collapsible'>\" : \"\";\r\n" +
            "			  html += GetRow(indent, \"<span class='ArrayBrace'>[</span>\"+clpsHtml, isPropertyContent);\r\n" +
            "			  for(var i = 0; i < obj.length; i++){\r\n" +
            "				html += ProcessObject(obj[i], indent + 1, i < (obj.length - 1), true, false);\r\n" +
            "			  }\r\n" +
            "			  clpsHtml = window.IsCollapsible ? \"</span>\" : \"\";\r\n" +
            "			  html += GetRow(indent, clpsHtml+\"<span class='ArrayBrace'>]</span>\"+comma);\r\n" +
            "			}\r\n" +
            "		  }else if(type == 'object'){\r\n" +
            "			if (obj == null){\r\n" +
            "				html += FormatLiteral(\"null\", \"\", comma, indent, isArray, \"Null\");\r\n" +
            "			}else if (obj.constructor == window._dateObj.constructor) { \r\n" +
            "				html += FormatLiteral(\"new Date(\" + obj.getTime() + \") /*\" + obj.toLocaleString()+\"*/\", \"\", comma, indent, isArray, \"Date\"); \r\n" +
            "			}else if (obj.constructor == window._regexpObj.constructor) {\r\n" +
            "				html += FormatLiteral(\"new RegExp(\" + obj + \")\", \"\", comma, indent, isArray, \"RegExp\"); \r\n" +
            "			}else{\r\n" +
            "			  var numProps = 0;\r\n" +
            "			  for(var prop in obj) numProps++;\r\n" +
            "			  if(numProps == 0){\r\n" +
            "				html += GetRow(indent, \"<span class='ObjectBrace'>{ }</span>\"+comma, isPropertyContent);\r\n" +
            "			  }else{\r\n" +
            "				clpsHtml = window.IsCollapsible ? \"<span><img style='cursor:pointer' src=\\\"\"+window.ImgExpanded+\"\\\" onClick=\\\"ExpImgClicked(this)\\\" /></span><span class='collapsible'>\" : \"\";\r\n" +
            "				html += GetRow(indent, \"<span class='ObjectBrace'>{</span>\"+clpsHtml, isPropertyContent);\r\n" +
            "				var j = 0;\r\n" +
            "				for(var prop in obj){\r\n" +
            "				  var quote = window.QuoteKeys ? \"\\\"\" : \"\";\r\n" +
            "				  html += GetRow(indent + 1, \"<span class='PropertyName'>\"+quote+prop+quote+\"</span>: \"+ProcessObject(obj[prop], indent + 1, ++j < numProps, false, true));\r\n" +
            "				}\r\n" +
            "				clpsHtml = window.IsCollapsible ? \"</span>\" : \"\";\r\n" +
            "				html += GetRow(indent, clpsHtml+\"<span class='ObjectBrace'>}</span>\"+comma);\r\n" +
            "			  }\r\n" +
            "			}\r\n" +
            "		  }else if(type == 'number'){\r\n" +
            "			html += FormatLiteral(obj, \"\", comma, indent, isArray, \"Number\");\r\n" +
            "		  }else if(type == 'boolean'){\r\n" +
            "			html += FormatLiteral(obj, \"\", comma, indent, isArray, \"Boolean\");\r\n" +
            "		  }else if(type == 'function'){\r\n" +
            "			if (obj.constructor == window._regexpObj.constructor) {\r\n" +
            "				html += FormatLiteral(\"new RegExp(\" + obj + \")\", \"\", comma, indent, isArray, \"RegExp\"); \r\n" +
            "			}else{\r\n" +
            "				obj = FormatFunction(indent, obj);\r\n" +
            "				html += FormatLiteral(obj, \"\", comma, indent, isArray, \"Function\");\r\n" +
            "			}\r\n" +
            "		  }else if(type == 'undefined'){\r\n" +
            "			html += FormatLiteral(\"undefined\", \"\", comma, indent, isArray, \"Null\");\r\n" +
            "		  }else{\r\n" +
            "			html += FormatLiteral(obj.toString().split(\"\\\\\").join(\"\\\\\\\\\").split('\"').join('\\\\\"'), \"\\\"\", comma, indent, isArray, \"String\");\r\n" +
            "		  }\r\n" +
            "		  return html;\r\n" +
            "		}\r\n" +
            "		\r\n" +
            "		function FormatLiteral(literal, quote, comma, indent, isArray, style){\r\n" +
            "		  if(typeof literal == 'string')\r\n" +
            "			literal = literal.split(\"<\").join(\"&lt;\").split(\">\").join(\"&gt;\");\r\n" +
            "		  var str = \"<span class='\"+style+\"'>\"+quote+literal+quote+comma+\"</span>\";\r\n" +
            "		  if(isArray) str = GetRow(indent, str);\r\n" +
            "		  return str;\r\n" +
            "		}\r\n" +
            "\r\n" +
            "		function FormatFunction(indent, obj){\r\n" +
            "		  var tabs = \"\";\r\n" +
            "		  for(var i = 0; i < indent; i++) tabs += window.TAB;\r\n" +
            "		  var funcStrArray = obj.toString().split(\"\\n\");\r\n" +
            "		  var str = \"\";\r\n" +
            "		  for(var i = 0; i < funcStrArray.length; i++){\r\n" +
            "			str += ((i==0)?\"\":tabs) + funcStrArray[i] + \"\\n\";\r\n" +
            "		  }\r\n" +
            "		  return str;\r\n" +
            "		}\r\n" +
            "\r\n" +
            "		function GetRow(indent, data, isPropertyContent){\r\n" +
            "		  var tabs = \"\";\r\n" +
            "		  for(var i = 0; i < indent && !isPropertyContent; i++) tabs += window.TAB;\r\n" +
            "		  if(data != null && data.length > 0 && data.charAt(data.length-1) != \"\\n\")\r\n" +
            "			data = data+\"\\n\";\r\n" +
            "		  return tabs+data;                       \r\n" +
            "		}\r\n" +
            "\r\n" +
            "		function CollapsibleViewClicked(){\r\n" +
            "		  $id(\"CollapsibleViewDetail\").style.visibility = $id(\"CollapsibleView\").checked ? \"visible\" : \"hidden\";\r\n" +
            "		  Process();\r\n" +
            "		}\r\n" +
            "\r\n" +
            "		function QuoteKeysClicked(){\r\n" +
            "		  window.QuoteKeys = $id(\"QuoteKeys\").checked;\r\n" +
            "		  Process();\r\n" +
            "		}\r\n" +
            "\r\n" +
            "		function CollapseAllClicked(){\r\n" +
            "		  EnsureIsPopulated();\r\n" +
            "		  TraverseChildren($id(\"Canvas\"), function(element){\r\n" +
            "			if(element.className == 'collapsible'){\r\n" +
            "			  MakeContentVisible(element, false);\r\n" +
            "			}\r\n" +
            "		  }, 0);\r\n" +
            "		}\r\n" +
            "\r\n" +
            "		function ExpandAllClicked(){\r\n" +
            "		  EnsureIsPopulated();\r\n" +
            "		  TraverseChildren($id(\"Canvas\"), function(element){\r\n" +
            "			if(element.className == 'collapsible'){\r\n" +
            "			  MakeContentVisible(element, true);\r\n" +
            "			}\r\n" +
            "		  }, 0);\r\n" +
            "		}\r\n" +
            "\r\n" +
            "		function MakeContentVisible(element, visible){\r\n" +
            "		  var img = element.previousSibling.firstChild;\r\n" +
            "		  if(!!img.tagName && img.tagName.toLowerCase() == \"img\"){\r\n" +
            "			element.style.display = visible ? 'inline' : 'none';\r\n" +
            "			element.previousSibling.firstChild.src = visible ? window.ImgExpanded : window.ImgCollapsed;\r\n" +
            "		  }\r\n" +
            "		}\r\n" +
            "\r\n" +
            "		function TraverseChildren(element, func, depth){\r\n" +
            "		  for(var i = 0; i < element.childNodes.length; i++){\r\n" +
            "			TraverseChildren(element.childNodes[i], func, depth + 1);\r\n" +
            "		  }\r\n" +
            "		  func(element, depth);\r\n" +
            "		}\r\n" +
            "\r\n" +
            "		function ExpImgClicked(img){\r\n" +
            "		  var container = img.parentNode.nextSibling;\r\n" +
            "		  if(!container) return;\r\n" +
            "		  var disp = \"none\";\r\n" +
            "		  var src = window.ImgCollapsed;\r\n" +
            "		  if(container.style.display == \"none\"){\r\n" +
            "			  disp = \"inline\";\r\n" +
            "			  src = window.ImgExpanded;\r\n" +
            "		  }\r\n" +
            "		  container.style.display = disp;\r\n" +
            "		  img.src = src;\r\n" +
            "		}\r\n" +
            "\r\n" +
            "		function CollapseLevel(level){\r\n" +
            "		  EnsureIsPopulated();\r\n" +
            "		  TraverseChildren($id(\"Canvas\"), function(element, depth){\r\n" +
            "			if(element.className == 'collapsible'){\r\n" +
            "			  if(depth >= level){\r\n" +
            "				MakeContentVisible(element, false);\r\n" +
            "			  }else{\r\n" +
            "				MakeContentVisible(element, true);  \r\n" +
            "			  }\r\n" +
            "			}\r\n" +
            "		  }, 0);\r\n" +
            "		}\r\n" +
            "\r\n" +
            "		function SetTab(){\r\n" +
            "		  var tabSize = 2; //json缩进单位\r\n" +
            "		  window.TAB = MultiplyString(tabSize, window.SINGLE_TAB);\r\n" +
            "		}\r\n" +
            "\r\n" +
            "		function EnsureIsPopulated(){\r\n" +
            "		  if(!$id(\"Canvas\").innerHTML) Process();\r\n" +
            "		}\r\n" +
            "\r\n" +
            "		function MultiplyString(num, str){\r\n" +
            "		  var sb =[];\r\n" +
            "		  for(var i = 0; i < num; i++){\r\n" +
            "			sb.push(str);\r\n" +
            "		  }\r\n" +
            "		  return sb.join(\"\");\r\n" +
            "		}\r\n" +
            "\r\n" +
            "		function SelectAllClicked(){\r\n" +
            "		  if(!!document.selection && !!document.selection.empty) {\r\n" +
            "			document.selection.empty();\r\n" +
            "		  } else if(window.getSelection) {\r\n" +
            "			var sel = window.getSelection();\r\n" +
            "			if(sel.removeAllRanges) {\r\n" +
            "			  window.getSelection().removeAllRanges();\r\n" +
            "			}\r\n" +
            "		  }\r\n" +
            "		  var range = \r\n" +
            "			  (!!document.body && !!document.body.createTextRange)\r\n" +
            "\r\n" +
            "				  ? document.body.createTextRange()\r\n" +
            "\r\n" +
            "				  : document.createRange();\r\n" +
            "		  if(!!range.selectNode)\r\n" +
            "			range.selectNode($id(\"Canvas\"));\r\n" +
            "		  else if(range.moveToElementText)\r\n" +
            "			range.moveToElementText($id(\"Canvas\"));\r\n" +
            "		  if(!!range.select)\r\n" +
            "			range.select($id(\"Canvas\"));\r\n" +
            "		  else\r\n" +
            "			window.getSelection().addRange(range);\r\n" +
            "		}\r\n" +
            "	</script>\r\n" +
            "</html>";
            #endregion

            return html;
        }

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(
            string section,
            string key,
            string def,
            StringBuilder retval,
            int size,
            string filePath);

        #region	 ini文件的读取方法

        private static string ReadIniData(string Section, string Key, string NoText, string iniFilePath)
        {
            if (File.Exists(iniFilePath))
            {
                StringBuilder temp = new StringBuilder(1024);
                GetPrivateProfileString(Section, Key, NoText, temp, 1024, iniFilePath);
                return temp.ToString();
            }
            else
            {
                return String.Empty;
            }
        }

        #endregion
    }
}
